//
//  CalendarViewController.swift
//  ZZUI
//
//  Created by 张文晏 on 2018/10/31.
//  Copyright © 2018 张文晏. All rights reserved.
//

import UIKit
import SnapKit

public class NCCalendar {
    
    static func topController(_ viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = viewController as? UINavigationController {
            return topController(nav.visibleViewController)
        }
        if let tab = viewController as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topController(selected)
            }
        }
        if let presented = viewController?.presentedViewController {
            return topController(presented)
        }
        return viewController
    }
    
    public static func showSingleMode(selectedDate: Date?, finishClosure: ((_ date: Date) -> Void)?) {
        let vc = CalendarViewController(selectionMode: .single)
        vc.modalPresentationStyle = .overCurrentContext
        vc.koyomi.select(date: selectedDate)
        vc.finishBySingleClosure = { finishClosure?($0) }
        topController()?.present(vc, animated: false)
    }
    
    public static func showSequenceMode(selectedDates: (Date?, Date?)?, finishClosure: ((_ from: Date, _ to: Date) -> Void)?) {
        let vc = CalendarViewController(selectionMode: .sequence)
        vc.modalPresentationStyle = .overCurrentContext
        vc.koyomi.select(date: selectedDates?.0, to: selectedDates?.1)
        vc.finishBySequenceClosure = { finishClosure?($0, $1) }
        topController()?.present(vc, animated: false)
    }
    
}

public class CalendarViewController: UIViewController {
    
    // MARK: - Subviews
    let contentView = UIView()
    lazy var currentMonthLabel: UILabel = {
        let label = UILabel()
        label.font = .systemFont(ofSize: 17)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    lazy var koyomi: Koyomi = {
        let v = Koyomi(
            frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 294),
            sectionSpace: 0,
            cellSpace: 0,
            inset: .zero,
            weekCellHeight: 30
        )
        v.setWeekFont(size: 12)
        v.setDayFont(size: 14)
        v.weekColor = UIColor(red: 102 / 255.0, green: 102 / 255.0, blue: 102 / 255.0, alpha: 1)
        v.weeks = ("周日", "周一", "周二", "周三", "周四", "周五", "周六")
        v.selectionMode = selectionMode
        v.selectedStyleColor = .init(hex: 0x006fff)
        return v
    }()
    
    var selectionMode: SelectionMode = .single {
        didSet {
            koyomi.selectionMode = selectionMode
        }
    }
    
    // MARK: - Variables
    var cancelClosure: (() -> Void)?
    var finishBySingleClosure: ((_ selectedDate: Date) -> Void)?
    var finishBySequenceClosure: ((_ from: Date, _ to: Date) -> Void)?
    
    
    convenience init(selectionMode: SelectionMode) {
        self.init()
        self.selectionMode = selectionMode
        self.koyomi.selectionMode = selectionMode
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    public override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        contentView.snp.updateConstraints { make in
            make.top.equalTo(self.view.snp.bottom).offset(-self.contentView.bounds.height)
        }
        UIView.animate(withDuration: 0.2, animations: {
            self.view.layoutIfNeeded()
        })
    }
    
    func setupUI() {
        view.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        view.addSubview(contentView)
        
        // current month label
        contentView.addSubview(currentMonthLabel)
        currentMonthLabel.snp.makeConstraints { make in
            make.top.equalTo(9)
            make.centerX.equalToSuperview()
            make.width.equalTo(70)
            make.height.equalTo(26)
        }
        currentMonthLabel.text = koyomi.currentDateString(withFormat: "yyyy.MM")
        
        // last month button
        let lastMonthBtn = UIButton()
        contentView.addSubview(lastMonthBtn)
        lastMonthBtn.snp.makeConstraints { make in
            make.trailing.equalTo(currentMonthLabel.snp.leading)
            make.centerY.equalTo(currentMonthLabel)
            make.height.equalTo(14)
            make.width.equalTo(48)
        }
        lastMonthBtn.setImage(NCUIBundle.image("ui_calendar_arrow_left_normal"), for: .normal)
        lastMonthBtn.addTarget(self, action: #selector(lastMonthAction), for: .touchUpInside)
        
        // next month button
        let nextMonthBtn = UIButton()
        contentView.addSubview(nextMonthBtn)
        nextMonthBtn.snp.makeConstraints { make in
            make.leading.equalTo(currentMonthLabel.snp.trailing)
            make.centerY.equalTo(currentMonthLabel)
            make.height.equalTo(14)
            make.width.equalTo(48)
        }
        nextMonthBtn.setImage(NCUIBundle.image("ui_calendar_arrow_right_normal"), for: .normal)
        nextMonthBtn.addTarget(self, action: #selector(nextMonthAction), for: .touchUpInside)
        
        // cancel button
        let cancelBtn = UIButton()
        contentView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.top.leading.equalToSuperview()
            make.width.equalTo(48)
            make.height.equalTo(44)
        }
        cancelBtn.setAttributedTitle(
            NSAttributedString(
                string: "取消",
                attributes: [
                    NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16),
                    NSAttributedString.Key.foregroundColor : UIColor.init(hex: 0x006fff)
                ]
            ),
            for: .normal
        )
        cancelBtn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        
        // finish button
        let finishBtn = UIButton()
        contentView.addSubview(finishBtn)
        finishBtn.snp.makeConstraints { make in
            make.top.trailing.equalToSuperview()
            make.width.equalTo(48)
            make.height.equalTo(44)
        }
        finishBtn.setAttributedTitle(
            NSAttributedString(
                string: "完成",
                attributes: [
                    .font : UIFont.systemFont(ofSize: 16),
                    .foregroundColor : UIColor.init(hex: 0x006fff)
                ]
            ),
            for: .normal
        )
        finishBtn.addTarget(self, action: #selector(finishAction), for: .touchUpInside)
        
        // line
        let line = UIView()
        contentView.addSubview(line)
        line.snp.makeConstraints { make in
            make.top.equalTo(43)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .init(hex: 0xeeeeee)
        
        // koyomi
        contentView.addSubview(koyomi)
        koyomi.snp.makeConstraints { make in
            make.top.equalTo(44)
            make.leading.trailing.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(contentView.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalToSuperview()
            }
            make.height.equalTo(294)
        }
        view.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(self.view.snp.bottom)
        }
        contentView.backgroundColor = .white
    }
    
    @objc func lastMonthAction() {
        koyomi.display(in: .previous)
        currentMonthLabel.text = koyomi.currentDateString(withFormat: "yyyy.MM")
    }
    
    @objc func nextMonthAction() {
        koyomi.display(in: .next)
        currentMonthLabel.text = koyomi.currentDateString(withFormat: "yyyy.MM")
    }
    
    @objc func cancelAction() {
        self.contentView.snp.updateConstraints{ make in
            make.top.equalTo(self.view.snp.bottom)
        }
        UIView.animate(withDuration: 0.2, animations: {
            self.view.layoutIfNeeded()
        }) { _ in
            self.dismiss(animated: false)
        }
    }
    
    @objc func finishAction() {
        switch koyomi.selectionMode {
        case .single:
            guard let date = koyomi.model.selectedDate else { return }
            finishBySingleClosure?(date)
        case .sequence:
            guard let start = koyomi.model.sequenceDates.start else { return }
            let end = koyomi.model.sequenceDates.end
            finishBySequenceClosure?(start, end ?? start)
        }
        cancelAction()
    }
}
